package com.nm.web.util;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.nm.commons.util.StringUtil;
import org.apache.commons.collections.map.HashedMap;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * Created by hewu on 2017/2/15 0015.
 */
public abstract class JsonHelper {

    /**
     * String转对象
     *
     * @param json
     * @param T
     * @param <T>
     * @return
     */
    public static <T> T from(String json, Class<T> T) {
        if (StringUtil.isNull(json)) {
            return null;
        }

        return new Gson().fromJson(json, T);
    }

    /**
     * 对象转Map
     *
     * @param t
     * @param <T>
     * @return
     */
    public static <T> Map<String, Object> toMap(T t) {

        if (t == null) {
            return null;
        }

        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        Map<String, Object> map = new HashedMap();

        Type type = new TypeToken<Map<String, Object>>() {
        }.getType();

        map = gson.fromJson(new Gson().toJson(t), type);
        return map;
    }

    /**
     * JsonObject转对象
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T fromJson(String json, Class<T> clazz) {

        return new Gson().fromJson(json, clazz);
    }
}
